package cryptogen

import (
	"bytes"
	"os"
	"os/exec"
	"path/filepath"
	"text/template"

	"gitee.com/extrame/fb-runner/util"
	"github.com/sirupsen/logrus"
)

func Generate(org *util.Organization, source, dest string) error {
	// cryptogen generate --config=./organizations/cryptogen/crypto-config-org2.yaml --output="organizations"
	logrus.Infoln("generate cryptogen", source, dest)
	cfg, err := generateTempCryptogenForOrg(org, source, os.TempDir())
	if err == nil {
		cmd := exec.Command("cryptogen", "generate", "--config="+cfg, "--output="+dest)
		var stdout bytes.Buffer
		cmd.Stdout = &stdout
		var stderr bytes.Buffer
		cmd.Stderr = &stderr
		err = cmd.Run()
		if err != nil {
			logrus.WithField("output", stdout.String()).WithField("errors", stderr.String()).WithError(err).Errorln("generate error")
		} else {
			logrus.WithField("output", stdout.String()).WithField("errors", stderr.String()).Infoln("generate success")
		}
	}

	return err
}

func generateTempCryptogenForOrg(org *util.Organization, source, dest string) (string, error) {

	t, err := template.ParseFiles(source)
	var cfg string
	if err == nil {
		var f *os.File
		cfg = filepath.Join(dest, org.GetKey()+"-"+filepath.Base(source))
		f, err = os.OpenFile(cfg, os.O_WRONLY|os.O_TRUNC|os.O_CREATE, 0644)
		if err == nil {
			err = t.Execute(f, org)
			f.Close()
		}
	}
	logrus.Infoln("生成临时文件：", cfg)
	return cfg, err
}
